package com.brother.realtime;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.Socket;
import java.net.SocketException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.io.LineNumberReader;

import org.apache.log4j.Logger;
import org.apache.xalan.templates.XUnresolvedVariable;

import com.brother.alarm.AlarmObserverImpl;
import com.brother.database.DataBase;
import com.brother.geocode.GeoCoder;
import com.brother.model.AlarmType;
import com.brother.model.Customer;
import com.brother.model.LatLngAddress;
import com.brother.model.LatLngPoint;
import com.brother.model.RealTimeData;
import com.brother.model.Signal;
import com.brother.model.Tip;
import com.brother.model.Tracker;
import com.brother.realtime.cache.ActionData;
import com.brother.realtime.cache.ParametersSetCache;
import com.brother.realtime.config.Config;
import com.brother.realtime.config.ConfigGEO;
import com.brother.realtime.config.ConfigReportInterval;
import com.brother.realtime.config.RequestCoordinateConfig;
import com.brother.realtime.config.RequestStatusConfig;
import com.brother.realtime.config.ReturnAddressConfig;
import com.brother.realtime.config.UpgradeFirmware;
import com.brother.service.AlarmService;
import com.brother.service.RealDataService;
import com.brother.service.TipService;
import com.brother.service.TrackerService;
import com.brother.util.CommonProperties;
import com.brother.util.Distance;
import com.brother.util.LatLngConverter;
import com.brother.util.MalaysiaAddress;
import com.brother.util.NigeriaAddress;

public class RealTimeDataProcessor implements Runnable {
	private SocketChannel socket;
	private Logger log = Logger.getLogger(this.getClass());
	private String address = null;
	private long lastRecievedTime = System.currentTimeMillis();
	private long lostSignalLimit = CommonProperties.getLostSignalTime();

	/**
	 * 是否是重复连接进来
	 */
	private boolean isReconnected = false;

	public RealTimeDataProcessor(SocketChannel socket2) {
		this.socket = socket2;
		configs = new ArrayList<Config>();
	}

	public String getAddress() {
		return this.address;
	}

	private TrackerService tks = new TrackerService();

	private String userTrackerId = null;
	private Customer user = null;

	public String getUserTrackerId() {
		return userTrackerId;
	}

	private List<Config> configs;

	public void addConfig(Config c) {
		this.configs.add(c);
	}

	private boolean stopped = false;
	private UpgradeFirmware upgradeWare;

	@Override
	public void run() {
		boolean keepAlive = false;

		address = this.socket.socket().getRemoteSocketAddress().toString();
		if (log.isDebugEnabled())
			log.debug("the keepAlive of socket connection " + address + " is :"
					+ keepAlive);

		try {
			String remoteAddr = address;
			ComandReader cmdr = new ComandReader(this.socket, remoteAddr);
			Config config = null;

			while (this.socket.isConnected() && !stopped) {
				try {
					if (this.configs.size() > 0) {
						config = this.configs.remove(0);
						if (log.isDebugEnabled()) {
							log.debug("write config :" + config);
						}
						if (config instanceof UpgradeFirmware) { // 升级固件
							upgradeWare = (UpgradeFirmware) config;
							new Thread() {
								public void run() {
									upgradeFirmware();
								}
							}.start();
						} else {
							System.out.println("writing command "
									+ this.userTrackerId + " "
									+ System.currentTimeMillis());
							ByteBuffer wb = ByteBuffer.wrap(config.getData());
							this.socket.write(wb);
							System.out.println("writing command end "
									+ this.userTrackerId + "   "
									+ System.currentTimeMillis());
						}
					}
					// cmdr.readOneCommand2();
					Command cmd = cmdr.readOneCommand2();
					if (cmd == null) {
						if (System.currentTimeMillis() - this.lastRecievedTime > lostSignalLimit) {
							break;
						}
						try {
							Thread.sleep(1000);
						} catch (InterruptedException e) {
							log.error(e);
						}
						continue;
					} else {
						lastRecievedTime = System.currentTimeMillis();
					}

					// System.out.println(cmd+"  address:"+remoteAddr);
					// 老协议 首次连接
					if (cmd instanceof GsnCommand) {
						userTrackerId = ((GsnCommand) cmd).getUserTrackerId();
						this.setTracker();
						if (this.tracker == null) {
							break;
						}
						cmdr.setTrackerId(this.tracker.getTrackerid());
						cmdr.setProtocol(this.tracker.getCarmodelId());
						ProcessorPool.getInstance()
								.removeProcessorByUserTrackerId(userTrackerId,
										this);

						if (userTrackerId != null) {
							this.addLoginTip(userTrackerId);
						}

						this.updateSignal(Signal.ok);
					} else if (cmd instanceof DataCommand) {// 为数据命令
						if (userTrackerId == null) {
							this.socket.close();
							log.info("no IMEI ,closed :" + remoteAddr);
							break;
						}
						saveRealtimeData((DataCommand) cmd);
					} else if (cmd instanceof DataCommandXuXun) {// 为新协议数据命令

						userTrackerId = ((DataCommandXuXun) cmd)
								.getUserTrackerId();
						this.setTracker();
						if (this.tracker == null) {
							break;
						}
						cmdr.setTrackerId(this.tracker.getTrackerid());
						cmdr.setProtocol(this.tracker.getCarmodelId());
						ProcessorPool.getInstance()
								.removeProcessorByUserTrackerId(userTrackerId,
										this);

						if (userTrackerId != null) {
							this.addLoginTip(userTrackerId);
						}
						this.updateSignal(Signal.ok);
						// ----------------------------
						if (userTrackerId == null) {
							this.socket.close();
							log.info("no IMEI ,closed :" + remoteAddr);
							break;
						}
						DataCommand tem = ConverDataCommandXuXunToDataCommand(((DataCommandXuXun) cmd));
						saveRealtimeData(tem);

					} else if (cmd instanceof MutilDataCommand) {
						if (userTrackerId == null) {
							this.socket.close();
							log.info("no IMEI ,closed :" + remoteAddr);
							break;
						}
						for (DataCommand c : ((MutilDataCommand) cmd)
								.getCommands()) {
							if (hasTheSameData(c)) {
								continue;
							}
							saveRealtimeData(c);
						}
					} else if (cmd instanceof ConfigStatusCommand) {
						if (userTrackerId == null) {
							this.socket.close();
							log.info("no IMEI ,closed :" + remoteAddr);
							break;
						}
						if (config instanceof ConfigReportInterval) {
							this.setReportIntervalSuc();
						} else if (config instanceof ConfigGEO) {
							this.setGEOSuc();
						}
						if (((ConfigStatusCommand) cmd).getStatus()
								.equalsIgnoreCase("ok")) {
							ParametersSetCache.getInstance().setSuccess(
									tracker.getTrackerid(), true,
									((ConfigStatusCommand) cmd).getText());
						}
						DataBase.closeThreadConnection();
					} else if (cmd instanceof ConfigRequestStatusCommand) {
						ParametersSetCache.getInstance().setSuccess(
								tracker.getTrackerid(), true,
								((ConfigRequestStatusCommand) cmd).getStatus());
					} else if (cmd instanceof RequestAddressCommand) {
						final String center = (new StringBuilder(
								String.valueOf(((RequestAddressCommand) cmd)
										.getLat()))).append(",")
								.append(((RequestAddressCommand) cmd).getLng())
								.toString();
						(new Thread() {
							public void run() {
								try {
									returnAddress(center);
								} catch (Exception ex) {
									log.error(ex);
								}
							}
						}).start();
					} else if (cmd instanceof LostSignalCommand) {
						if (userTrackerId == null) {
							this.socket.close();
							log.info("no IMEI ,lost signal, closed :"
									+ remoteAddr);
							break;
						}
						this.updateSignal(Signal.na);
						// System.out.println("Lost signal for IMEI:"+this.userTrackerId+" address:"+remoteAddr);
						log.info("Lost signal for IMEI:" + this.userTrackerId
								+ " address:" + remoteAddr);
						break;
					} else if (cmd instanceof HeartbreakCommand) {
						if (userTrackerId != null) {
							this.updateSignal(Signal.ok);
						}
						// log.info(remoteAddr+" HeartbreakCommand ....");

						try {
							int time = ((int) ((HeartbreakCommand) cmd)
									.getInterTime() / 1000);
							if ((time == CommonProperties
									.getFirstServerOutputTime())
									|| (time > CommonProperties
											.getServerOutputInterval() && time
											% CommonProperties
													.getServerOutputInterval() == 0)) {
								// outs.write("56".getBytes());
							}
							Thread.sleep(2000);
						} catch (InterruptedException e) {
							log.error(e);
						}
					} else if (cmd instanceof ReqTrackerVerCommand) {
						ReqTrackerVerCommand verCmd = (ReqTrackerVerCommand) cmd;
						ParametersSetCache.getInstance().setSuccess(
								tracker.getTrackerid(), true,
								verCmd.getVersion() + "," + verCmd.getCsq());
					} else if (cmd instanceof UpgradeFrameStatusCommand) {
						UpgradeFrameStatusCommand upCmd = (UpgradeFrameStatusCommand) cmd;
						if (upCmd.getStatus().equalsIgnoreCase("ok")) {
							this.upgradeStatus = UPGRADE_STATUS_RECEIVE_OK;
							this.currentFrame = upCmd.getFrame();
						} else {
							this.upgradeStatus = UPGRADE_STATUS_RECEIVE_ERROR;
							this.currentFrame = upCmd.getFrame();
						}

					} else if (cmd instanceof ThirdPartySOSCommand) { // SOS报警
						save3PartyAlarm(AlarmType.SOS_Alarm);
					} else if (cmd instanceof ThirdPartyOverSpeedCommand) { // over
																			// speed报警
						save3PartyAlarm(AlarmType.Over_Speed_Alarm);
					} else if (cmd instanceof ThirdPartyLowBatteryCommand) { // low
																				// battery报警
						save3PartyAlarm(AlarmType.Low_Power_Alarm);
					}

					// System.out.println(remoteAddr+"The Data is:"+userTrackerId);
				} catch (SocketException e) {
					log.error(e);
					break;
				} catch (IOException e) {
					log.error(e);
					break;
				}
			}

		} catch (Exception ex) {
			log.error("", ex);
		} finally {
			try {
				if (log.isDebugEnabled())
					log.debug("close the client socket :" + address + " imei="
							+ this.userTrackerId);
				this.socket.close();
				this.socket.socket().close();
			} catch (IOException e) {
				log.error("imei=" + this.userTrackerId, e);
			}
		}
		log.debug(this.userTrackerId + " updating signal " + Signal.na.name()
				+ ", isReconnected: " + this.isReconnected);
		if (!isReconnected) {
			this.addLogoutTip();
			this.updateSignal(Signal.na);
		}
		ProcessorPool.getInstance().removeProcessor(this);
	}

	private void save3PartyAlarm(final AlarmType alarm) {
		if (tracker == null) {
			return;
		}
		try {
			RealDataService rs = new RealDataService();
			final RealTimeData data = rs.setSosAlarmFor3Party(this.tracker);
			if (data == null) {
				return;
			}
			data.setState(alarm.name());
			new Thread() {
				public void run() {
					try {
						AlarmEmailSender.sendMail(alarm, data, "en");
					} catch (Exception e) {
						log.error(e);
					}
				}
			}.start();
			rs.insertData(data);
		} catch (Exception e) {
			log.error("", e);
		} finally {
			DataBase.closeThreadConnection();
		}
	}

	private boolean hasTheSameData(DataCommand c) {
		// TODO Auto-generated method stub
		return false;
	}

	private void setGEOSuc() {
		if (tracker != null) {
			AlarmService as = new AlarmService();
			as.updateGeoAlarmSucStatus(1, tracker.getTrackerid());
			DataBase.closeThreadConnection();
		}
	}

	private void updateSignal(Signal sgl) {
		if (tracker != null) {
			RealDataService rs = new RealDataService();
			rs.updateLastDataSignal(sgl, tracker.getTrackerid());
			this.updateMileage(sgl);
			DataBase.closeThreadConnection();
		}
	}

	private void setReportIntervalSuc() {
		if (tracker != null) {
			TrackerService tks = new TrackerService();
			tks.updateIntervalSetStatus(1, this.tracker.getTrackerid());
			DataBase.closeThreadConnection();
		}
	}

	private void addLogoutTip() {
		// TODO Auto-generated method stub

	}

	private void saveRealtimeData(DataCommand cmd) {
		RealDataService rs = new RealDataService();

		AlarmObserverImpl alo = new AlarmObserverImpl();

		final RealTimeData data = new RealTimeData();

		data.setOrient(cmd.getOrient());
		data.setAlarmObserver(alo);
		DecimalFormat nf1 = new DecimalFormat("00");
		data.setOrig_lat(nf1.format((int) Math.abs(cmd.getLat()))
				+ Float.toString(Math.abs(LatLngConverter.toFen(cmd.getLat()))));
		data.setLatOrient(cmd.getLatOrient());
		data.setLat(cmd.getLat());
		DecimalFormat nf = new DecimalFormat("000");

		data.setOrig_lng(nf.format(Math.abs((int) Math.abs(cmd.getLng())))
				+ Float.toString(Math.abs(LatLngConverter.toFen(cmd.getLng()))));
		data.setLng(cmd.getLng());
		data.setLngOrient(cmd.getLngOrient());

		data.setTrackerid(this.tracker.getTrackerid());
		data.setState(cmd.getFlag());
		data.setSignal(Signal.ok.name());
		data.setSpeed(cmd.getSpeed());

		data.setDistance("0");
		data.setTraceDateTime(cmd.getDate());
		data.setLanguage(user.getLocale());
		
		data.setBattery(cmd.getBattery());
		data.setVoltage(cmd.getVoltage());
     	data.setFuel(cmd.getFuel());
		data.setAd2(cmd.getAd2());
		data.setTemp(cmd.getTemp());
		data.setFlag(cmd.getFlag());
		
		
		data.ckeckTriggerredAlarm();
		if (data.getState().equalsIgnoreCase(AlarmType.GPS_Pos.name())) {
			data.setState(cmd.getFlag());
		}
		if (data.getState().equalsIgnoreCase(AlarmType.GPS_Pos.name())) {
			data.setState("");
		}

		if (!data.getState().equals("")
				&& !data.getState().equalsIgnoreCase(AlarmType.GPS_Pos.name())) {
			if ((!data.getState().equalsIgnoreCase(AlarmType.ACC_ON.name()))
					&& (!data.getState().equalsIgnoreCase(
							AlarmType.DOOR_OPENED.name()))
					&& (!data.getState().equalsIgnoreCase(
							AlarmType.ACC_OFF.name()))
					&& (!data.getState().equalsIgnoreCase(
							AlarmType.DOOR_CLOSED.name()))) {
				new Thread() {
					public void run() {
						try {
							AlarmEmailSender.sendMail(
									AlarmType.valueOf(data.getState()), data,
									"en");
						} catch (Exception e) {
							log.error(e);
						}
					}
				}.start();
			}
		}
		/*
		 * Tracker tker = null; if(this.tracker != null &&
		 * this.tracker.getMileUpdate() != null){ tker =
		 * this.tks.getTrackerByFieldName("trackerId",
		 * this.tracker.getTrackerid()); float mileage = tker.getMileage();
		 * LatLngPoint from = new LatLngPoint(); int lngSign =
		 * data.getLngOrient().equals("W") ? -1 : 1; int latSign =
		 * data.getLatOrient().equals("S") ? -1 : 1;
		 * from.setLat(data.getLat()*latSign);
		 * from.setLng(data.getLng()*lngSign);
		 * 
		 * LatLngPoint to = new LatLngPoint(); List<RealTimeData> rl = new
		 * ArrayList(); rs.isConnected(tracker.getTrackerid() , rl);
		 * if(rl.size() > 0){ lngSign = rl.get(0).getLngOrient().equals("W") ?
		 * -1 : 1; latSign = rl.get(0).getLatOrient().equals("S") ? -1 : 1;
		 * to.setLat(rl.get(0).getLat()*latSign);
		 * to.setLng(rl.get(0).getLng()*lngSign); mileage = (float) (mileage +
		 * Distance.distance(from, to)/1000);
		 * tks.setMileage(this.tracker.getTrackerid(), mileage); } }
		 */
		if (cmd.getAccStat() != null) {
			this.tks.updateAccStatus(this.tracker.getTrackerid(),
					"" + cmd.getAccStat());
		}
		if (cmd.getDoorStat() != null) {
			this.tks.updateDoorStatus(this.tracker.getTrackerid(),
					"" + cmd.getDoorStat());
		}
		rs.insertData(data);
		/*
		 * if(tker == null){ this.updateMileage(Signal.ok); }
		 */
		this.updateMileage(Signal.ok);
		DataBase.closeThreadConnection();
	}

	/**
	 * 更新里程
	 * 
	 * @param sgl
	 */
	private Tracker updateMileage(Signal sgl) {
		Tracker tker = this.tks.getTrackerByFieldName("trackerid",
				this.tracker.getTrackerid());
		if (tker.getMileUpdate() == null
				|| (sgl == Signal.na)
				|| ((System.currentTimeMillis() - tker.getMileUpdate()
						.getTime()) / 1000 > CommonProperties
						.getMileageUpdateTime())) { // 超过里程更新时间
			MileageUpdator.getInstance().addTask(this.tracker.getTrackerid());
		}
		return tker;
	}

	/**
	 * @param userTrackerId
	 *            鐢ㄦ埛杈撳叆鐨勫敮涓�爣蹇楃爜锛屼竴鑸负鎵嬫満鍙风爜,ime
	 */
	private void addLoginTip(String userTrackerId) {
		TipService ts = new TipService();
		ts.addTip(userTrackerId, Tip.KeyNames.LOGIN);
		DataBase.closeThreadConnection();
	}

	private void setTracker() {
		try {
			TrackerService tks = new TrackerService();
			tracker = tks.getTrackerByFieldName("userTrackerId", userTrackerId);

			com.brother.service.UserService us = new com.brother.service.UserService();
			user = us.GetUserByUserId(tracker.getUserid());
		} catch (Exception e) {
			log.error("IMEI=" + userTrackerId, e);
		}
		DataBase.closeThreadConnection();
	}

	public void setStopped(boolean s) {
		this.stopped = s;
	}

	public boolean isStopped() {
		return this.stopped;
	}

	public boolean isReconnected() {
		return isReconnected;
	}

	public void setReconnected(boolean isReconnected) {
		this.isReconnected = isReconnected;
	}

	private Tracker tracker = null;

	public Tracker getTracker() {
		return tracker;
	}

	public boolean isLogin() {
		return tracker != null;
	}

	private int upgradeStatus = 0;
	private int currentFrame = 1;

	public static final int UPGRADE_STATUS_SEND = 1; // 帧已经发送
	public static final int UPGRADE_STATUS_RECEIVE_OK = 2; // 帧发送成功
	public static final int UPGRADE_STATUS_RECEIVE_ERROR = 3; // 帧发送失败

	public void upgradeFirmware() {
		if (this.tracker == null) {
			return;
		}
		long sendTime = 0; // 开始发送的时间
		int repeatTimes = 0; // 重发次数
		log.debug("Tracker " + this.tracker.getTrackerName()
				+ " begin to upgrade firmware! size="
				+ this.upgradeWare.getSize());
		this.upgradeWare.setPos(0);
		upgradeStatus = 0;
		currentFrame = 1;
		while (this.upgradeWare.hasData()) { // 还有数据没有发送给客户端
			try {

				if (upgradeStatus == 0) { // 初始第一帧
					upgradeStatus = UPGRADE_STATUS_SEND;
					currentFrame = this.upgradeWare.getCurrentOrder() + 1;
					log.debug("Tracker " + this.tracker.getTrackerName()
							+ " is writing frame " + currentFrame);
					this.socket.write(ByteBuffer.wrap(this.upgradeWare
							.getData()));
					sendTime = System.currentTimeMillis();
					repeatTimes = 1;
					ParametersSetCache
							.getInstance()
							.setSuccess(
									tracker.getTrackerid(),
									false,
									"percent:"
											+ ((float) this.upgradeWare
													.getCurrentOrder() / (float) (this.upgradeWare
													.getSize() / 518))); // 设置百分比
					Thread.sleep(2000);
					continue;
				} else if (upgradeStatus == UPGRADE_STATUS_RECEIVE_OK) { // 前面一帧已经成功发送了
					this.upgradeWare.setOrder(this.currentFrame); // 跟踪器帧数从1开始,
																	// 成功之后增加序列
					if (!this.upgradeWare.hasData()) {
						log.debug("There is no data for upgrade "
								+ (this.tracker != null ? this.tracker
										.getTrackerName()
										: "xxxxx(tracker not initialize)"));
						break;
					}
					upgradeStatus = UPGRADE_STATUS_SEND;
					currentFrame = this.upgradeWare.getCurrentOrder() + 1; // 跟踪器帧数从1开始
					log.debug("Tracker " + this.tracker.getTrackerName()
							+ " is writing frame " + currentFrame);
					this.socket.write(ByteBuffer.wrap(this.upgradeWare
							.getData()));
					sendTime = System.currentTimeMillis();
					repeatTimes = 1;
					ParametersSetCache
							.getInstance()
							.setSuccess(
									tracker.getTrackerid(),
									false,
									"percent:"
											+ ((float) this.upgradeWare
													.getCurrentOrder() / (float) (this.upgradeWare
													.getSize() / 518))); // 设置百分比
					Thread.sleep(2000);
					continue;
				}

				if (upgradeStatus == UPGRADE_STATUS_RECEIVE_ERROR) { // tracker返回错误代码,
																		// 重发
					log.debug("Can't upgrade the firmware for tracker "
							+ (this.tracker != null ? this.tracker
									.getTrackerName()
									: "xxxxx(tracker not initialize)")
							+ ", tracker error");
					upgradeStatus = UPGRADE_STATUS_SEND;
					currentFrame = this.upgradeWare.getCurrentOrder() + 1;
					this.socket.write(ByteBuffer.wrap(this.upgradeWare
							.getData()));
					sendTime = System.currentTimeMillis();
					repeatTimes++;
					Thread.sleep(2000);
					continue;
				}
				if (repeatTimes >= 3
						&& ((System.currentTimeMillis() - sendTime) > Integer
								.parseInt(CommonProperties
										.getValue("firmware.upgrade.resend.interval")))) { // 超时发送没有反应
					ParametersSetCache.getInstance().setSuccess(
							tracker.getTrackerid(), true, "error"); // 确认失败
					DataBase.closeThreadConnection();
					log.debug("Can't upgrade the firmware for tracker "
							+ (this.tracker != null ? this.tracker
									.getTrackerName()
									: "xxxxx(tracker not initialize)")
							+ ", time expired");
					break;
				}

				if ((System.currentTimeMillis() - sendTime) > Integer
						.parseInt(CommonProperties
								.getValue("firmware.upgrade.resend.interval"))) { // 超时发送没有反应,重发
					log.debug("Tracker " + this.tracker.getTrackerName()
							+ " is rewriting frame " + currentFrame);
					upgradeStatus = UPGRADE_STATUS_SEND;
					currentFrame = this.upgradeWare.getCurrentOrder() + 1;
					this.socket.write(ByteBuffer.wrap(this.upgradeWare
							.getData()));
					sendTime = System.currentTimeMillis();
					repeatTimes++;
					Thread.sleep(2000);
					continue;
				}
				Thread.sleep(2000);
			} catch (Exception e) {
				ParametersSetCache.getInstance().setSuccess(
						tracker.getTrackerid(), true, "error");
				DataBase.closeThreadConnection();
				log.error("Can't upgrade the firmware for tracker "
						+ (this.tracker != null ? this.tracker.getTrackerName()
								: "xxxxx(tracker not initialize)"), e);
				break;
			}
		}
		if (!this.upgradeWare.hasData()) { // 发送完毕
			log.debug("Tracker " + this.tracker.getTrackerName()
					+ " upgrade firmware successfully ");
			ParametersSetCache.getInstance().setSuccess(tracker.getTrackerid(),
					true, "ok"); // 确认升级成功
		}
		log.debug("end of upgrading firmware for tracker "
				+ this.tracker.getTrackerName());
	}

	public void returnAddress(String center) throws IOException {
		String[] ps = center.split(",");
		float lat = Float.parseFloat(ps[0]);
		float lng = Float.parseFloat(ps[1]);
		String geoAddr = null;
		LatLngAddress addr = GeoCoder.getAddress(lat + "", lng + "", "en");
		DataBase.closeThreadConnection();
		if (addr != null) {
			geoAddr = addr.getAddress();
			if (geoAddr != null) {
				ReturnAddressConfig addrConf = new ReturnAddressConfig();
				addrConf.setAddress(geoAddr);
				addConfig(addrConf);
				return;
			}
		}
		if (NigeriaAddress.getInstance().isIntesect(lat, lng)) {
			geoAddr = NigeriaAddress.getInstance().getAddressByDB(lat, lng);
			GeoCoder.saveAddress(lat + "", lng + "", geoAddr, "en", null, null);
			DataBase.closeThreadConnection();
		} else if (MalaysiaAddress.getInstance().isIntesect(lat, lng)) {
			geoAddr = MalaysiaAddress.getInstance().getAddressByDB(lat, lng);
			GeoCoder.saveAddress(lat + "", lng + "", geoAddr, "en", null, null);
			DataBase.closeThreadConnection();
		}
		if (geoAddr != null) {
			ReturnAddressConfig addrConf = new ReturnAddressConfig();
			addrConf.setAddress(geoAddr);
			addConfig(addrConf);
			return;
		}
		String locale = "en";
		String httpUrl = (new StringBuilder(
				"http://maps.google.com/maps/geo?output=json&oe=utf-8&ll="))
				.append(center)
				.append("&key=")
				.append(CommonProperties.getGoogleMapKey(
						"www.smart-tracking.com").replaceAll(" ", "%20"))
				.append("&mapclient=jsapi&hl=").append(locale)
				.append("&callback=_xdc_._2g9bgqp7l").toString();
		URL url = new URL(httpUrl);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("GET");
		conn.setRequestProperty("Content-Type",
				"text/javascript; charset=UTF-8");
		conn.setRequestProperty(
				"User-Agent",
				"\tMozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3 (.NET CLR 3.5.30729)");
		conn.setRequestProperty("Accept",
				"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
		conn.setRequestProperty("Host", "maps.google.com");
		InputStream in = conn.getInputStream();
		BufferedReader bf = new BufferedReader(new InputStreamReader(in));
		String line = null;
		StringBuilder sb = new StringBuilder();
		while ((line = bf.readLine()) != null)
			sb.append(line);
		String address = "";
		if (sb.indexOf("\"address\": \"") > -1) {
			int start = sb.indexOf("\"address\": \"")
					+ "\"address\": \"".length();
			address = sb.substring(start, sb.indexOf("\"", start));
		}
		in.close();
		ReturnAddressConfig addrConf = new ReturnAddressConfig();
		addrConf.setAddress(address);
		addConfig(addrConf);
		GeoCoder.saveAddress(lat + "", lng + "", address, "en", null, null);
		DataBase.closeThreadConnection();
	}

	public DataCommand ConverDataCommandXuXunToDataCommand(
			DataCommandXuXun xuxun) {
		DataCommand cmd = new DataCommand();
		// cmd.setUserTrackerId(xuxun.getUserTrackerId());
		if (xuxun != null) {
			cmd.setDate(xuxun.getDate());

			cmd.setLat(xuxun.getLat());// 经度

			cmd.setOrig_lat(xuxun.getOrig_lat());
			cmd.setLatOrient(xuxun.getLatOrient());
			cmd.setLat(xuxun.getLat());

			// cmd.setLatOrient(xuxun.getOrig_lat());
			cmd.setLng(xuxun.getLng());// 维度
			cmd.setOrig_lng(xuxun.getOrig_lng());
			cmd.setLngOrient(xuxun.getLngOrient());

			cmd.setSpeed(xuxun.getSpeed());
			cmd.setOrient(xuxun.getOrient());// 方向
			cmd.setFlag(xuxun.getFlag());
		}

		return cmd;

	}
}
